<template>
  <view class="order-btns-wrapper">
    <ve-operate-list operate-storagekey="order_operate_record" :staticBtnIsReverse="true" :operates="operates" :record="record" />
  </view>

  <!-- 作废订单 -->
  <invalid-order-modal ref="invalidOrderModalRef" @ok="emit('ok')" />
  <!-- 选择车牌号 -->
  <change-license-modal ref="changeLicenseModalRef" :orderCarInfoList="orderCarInfoList" @ok="changeLicenseOk" />
  <!-- 铁行渠道自动维护订单拦截弹窗 -->
  <tiexing-order-intercept ref="tiexingOrderInterceptRef" />
  <!-- 生成电子合同 -->
  <generate-contract-popup ref="generateContractPopupRef" />
</template>

<script setup>
  import changeLicenseModal from '@/pages/order/components/change-license-modal.vue'
  import invalidOrderModal from './modals/invalid-order-modal.vue'
  import tiexingOrderIntercept from './modals/tiexing-order-intercept.vue'
  import generateContractPopup from '@/pages/order/components/generate-contract-popup.vue'

  import { ref } from 'vue'
  import { serializeUrlParams } from '@/utils'
  import {
    finishCheckAPI,
    finishAPI,
    orderGoodEvaluate,
    getInterceptRefControl,
    getReCarKey,
    getCarControlSms,
    carReplaceListAPI,
    addCustomTag,
    verifyOrderApi,
  } from '@/api/order/sOrder'
  import useToast from '@/hooks/useToast'
  import { orderIsMaintenance, orderIsTiexing } from '../../tools.js'
  import { map } from 'lodash'
  import { usePermission } from '@/hooks/usePermission'
  import { userStore } from '@/stores/modules/user'

  const props = defineProps({
    record: {
      type: Object,
      default: () => {},
    },
    admin: {
      type: String,
      default: '',
    },
    isAdminRole: {
      type: Boolean,
      default: false,
    },
  })
  const emit = defineEmits(['ok'])
  const userInfoStore = userStore()

  // 铁行渠道自动维护订单拦截弹窗
  const tiexingOrderInterceptRef = ref()

  // 作废订单
  const invalidOrderModalRef = ref()
  const invalidOrderFn = () => {
    invalidOrderModalRef.value.open(props.record)
  }

  // 修改车牌号判断订单是否有换车操作弹框
  const changeLicenseModalRef = ref()
  // 换车记录列表
  const orderCarInfoList = ref([])
  const editCarLicenseNo = (record) => {
    carReplaceListAPI({ id: record.id }).then((res) => {
      let result = res.result
      // 是否为换车
      if (result.orderCarInfoList?.length > 1) {
        orderCarInfoList.value = result.orderCarInfoList.map((item) => {
          return {
            ...item,
            label: item.licenseNo,
            value: item.id,
          }
        })
        changeLicenseModalRef.value.open(record)
      } else {
        changeLicenseOk(record)
      }
    })
  }
  // 跳转选择车牌号页面
  const changeLicenseOk = (record) => {
    let orderInfo = {
      id: record.id,
      siteId: record.siteId,
      siteName: record.siteName,
      startTime: record.startTime,
      endTime: record.endTime,
      rentDays: record.rentDays,
      carSource: record.carSource,
      carSourceName: record.carSourceName,
      orderSourceName: record.orderSourceName,
      oldOrderCarId: record.oldOrderCarId,
      isEditLicenseNo: true, // 修改车牌号标识
      orderStatus: record.orderStatus,
      // 订单获取方式
      orderAcquisitionTypeName: record.orderAcquisitionTypeName,
      // 铁行相关配置
      carLicenseNo: record.carLicenseNo,
      channelOrderMaintenance: record.channelOrderMaintenance,
      carModelName: record.carModelName,
      channelOrderCode: record.channelOrderCode,
      channelType: record.channelType,
      orderSource: record.orderSource,
    }
    let paramStr = serializeUrlParams({
      mode: 'platoon',
      type: 'short-order',
      data_json: JSON.stringify(orderInfo),
      orderInfo_json: JSON.stringify(orderInfo),
    })
    uni.navigateTo({
      url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
    })
  }
  // 是否已同步车辆
  const hasRercordCar = (record, operateStr) => {
    if (record.carId) {
      return true
    } else {
      uni.showToast({
        icon: 'none',
        title: `当前车辆为渠道车辆，请先同平台车辆匹配后再${operateStr}`,
      })
      return false
    }
  }
  // 排车 & 改排
  const platoonCarFn = (record) => {
    if ([10, 100].includes(record.orderStatus)) {
      // 跳转选择车牌号页面
      let orderInfo = {
        id: record.id,
        // 当前选中的车辆 id
        platoonCarId: record.carId,
        carId: record.carId,
        siteId: record.siteId,
        siteName: record.siteName,
        modelId: record.carModelId,
        modelName: record.carModelName,
        startTime: record.startTime,
        endTime: record.endTime,
        rentDays: record.rentDays,
        carSource: record.carSource,
        carSourceName: record.carSourceName,
        orderSourceName: record.orderSourceName,
        // 订单获取方式
        orderAcquisitionTypeName: record.orderAcquisitionTypeName,
        // 铁行相关配置
        orderStatus: record.orderStatus,
        carLicenseNo: record.carLicenseNo,
        channelOrderMaintenance: record.channelOrderMaintenance,
        carModelName: record.carModelName,
        channelOrderCode: record.channelOrderCode,
        channelType: record.channelType,
        orderSource: record.orderSource,
      }
      let paramStr = serializeUrlParams({
        mode: 'platoon',
        type: 'short-order',
        data_json: JSON.stringify(orderInfo),
        orderInfo_json: JSON.stringify(orderInfo),
      })
      uni.navigateTo({
        url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
      })
    }
  }

  // 修改自定义标签
  const customLabelFn = (record, value) => {
    addCustomTag({
      id: record.id,
      customLabelList: value,
    })
      .then(() => {
        uni.showToast({
          title: '添加成功',
          icon: 'none',
        })
        // 刷新页面
        uni.$emit('loadData')
        // 订单热更新
        uni.$emit('order_hotUpdate')
      })
      .catch(() => {
        uni.showToast({
          title: '添加失败',
          icon: 'none',
        })
      })
  }

  // 手动生成电子合同
  const generateContractPopupRef = ref(null)
  const handleGenerateContract = (record) => {
    generateContractPopupRef.value.show(record, 'shortOrder')
  }

  const operates = ref([
    {
      label: '排车',
      permission: 'svmsapp:order:short-order.platooncar',
      show: (record) => [10].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
      method: (record) => {
        platoonCarFn(record)
      },
    },
    {
      label: '交车',
      permission: 'svmsapp:order:short-order.givecar',
      show: (record) => [100].includes(record.orderStatus) && record.isCarHouseKeepOpen === 0 && record.autoCancelOperate == 1,
      method: (record) => {
        // 自动维护的铁行渠道订单是否可以交还车 0：否 1:是
        if (tiexingOrderInterceptRef.value.open(record, 'givecar')) return
        if (hasRercordCar(record, '交车')) {
          uni.navigateTo({ url: `/pages/order/short-order/give-car?id=${record.id}` })
        }
      },
    },
    {
      label: '还车',
      permission: 'svmsapp:order:short-order.returncar',
      show: (record) => [200].includes(record.orderStatus) && record.isCarHouseKeepOpen === 0 && record.autoCancelOperate == 1,
      method: (record) => {
        // 自动维护的铁行渠道订单是否可以交还车 0：否 1:是
        if (tiexingOrderInterceptRef.value.open(record, 'returnCar')) return
        if (hasRercordCar(record, '还车')) {
          uni.navigateTo({ url: `/pages/order/short-order/return-car?id=${record.id}` })
        }
      },
    },
    {
      label: '完成',
      permission: 'svmsapp:order:short-order.complete',
      show: (record) => [300].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
      method: (record) => {
        finishCheckAPI({ id: record.id }).then((res) => {
          const { feeFlag, depoistFlag } = res.result
          let content = '请确认当前订单是否已完成？'
          let okText = '确认'
          if (feeFlag) {
            content = '当前订单还有未完成费用，请先完成费用收/付款，再进行完成操作'
            okText = '结算'
          } else if (depoistFlag) {
            // 目前判断不会走到这一步，因为押金也属于费用
            content = '当前订单租车押金、违章押金应退未退，请完成押金退款'
            okText = '退押金'
          }
          uni.showModal({
            title: '完成订单',
            content: content,
            cancelText: '取消',
            confirmText: okText,
            success(res) {
              if (res.confirm) {
                if (okText == '结算') {
                  uni.navigateTo({
                    url: '/pages/order/short-order/detail/index?id=' + record.id + '&tab=expense',
                  })
                } else if (okText == '退押金') {
                  let idList = JSON.stringify(record.depositFeeIdList)
                  uni.navigateTo({
                    url: `/pages/order/short-order/detail/confirmExpenses?idList=${idList}&id=${record.id}`,
                  })
                } else {
                  finishAPI({ id: record.id }).then(() => {
                    useToast({
                      title: '完成成功',
                    }).then(() => {
                      emit('ok')
                    })
                  })
                }
              }
            },
          })
        })
      },
    },
    {
      label: '修改订单',
      permission: 'svmsapp:order:short-order.edit',
      show: (record) => [10, 100, 200, 300, 1000].includes(record.orderStatus),
      method: (record) => {
        uni.navigateTo({ url: `/pages/order/short-order/form/edit?id=${record.id}` })
      },
    },
    {
      label: '结算\\修改费用',
      permission: 'svmsapp:order:short-order.confirmfee',
      show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
      method: (record) => {
        uni.navigateTo({
          url: `/pages/order/short-order/detail/index?id=${record.id}&tab=expense&orderId=${record.id}&bizType=1`,
        })
      },
    },
    {
      label: '自定义标签',
      permission: 'svmsapp:order:short-order.customlabel',
      method: (record) => {
        uni.navigateTo({
          url: '/pages/utils/selector',
          events: {
            selectorConfirm: (value, label, option = {}) => {
              customLabelFn(record, value)
            },
          },
          success: (res) => {
            // 传递数据
            res.eventChannel.emit('selectorInit', {
              type: 'customLabel',
              params: {},
              value: map(record.customLabelList, String),
              multiple: true,
              disabledValue: undefined,
              config: {},
              required: false,
            })
          },
        })
      },
    },
    {
      label: '添加用户缴费',
      permission: 'svmsapp:order:short-order.addfee',
      show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
      method: (record) => {
        uni.navigateTo({ url: `/pages/order/short-order/add-fees?id=${record.id}` })
      },
    },
    {
      label: '添加备注',
      // permission: 'svmsapp:order:short-order.addremark',
      show: (record) => {
        if (record.isCarHouseKeepOpen === 1) {
          return true
        } else {
          return usePermission('svmsapp:order:short-order.addremark')
        }
      },
      method: (record) => {
        uni.navigateTo({ url: `/pages/order/short-order/add-remark?id=${record.id}` })
      },
    },
    {
      label: '订单续租',
      permission: 'svmsapp:order:short-order.relet',
      show: (record) => [200].includes(record.orderStatus),
      method: (record) => {
        if (hasRercordCar(record, '续租')) {
          uni.navigateTo({ url: `/pages/order/short-order/relet-order?id=${record.id}` })
        }
      },
    },
    {
      label: '订单换车',
      permission: 'svmsapp:order:short-order.changecar',
      show: (record) => [200].includes(record.orderStatus) && record.isCarHouseKeepOpen === 0,
      method: (record) => {
        // 自动维护的铁行渠道订单是否可以交还车 0：否 1:是
        if (tiexingOrderInterceptRef.value.open(record, 'changecar')) return
        if (hasRercordCar(record, '换车')) {
          uni.navigateTo({ url: `/pages/order/short-order/change-car?id=${record.id}` })
        }
      },
    },
    {
      label: '新增违章',
      permission: 'svmsapp:order:short-order.addviolation',
      show: (record) => [200, 300, 1000].includes(record.orderStatus),
      method: (record) => {
        if (hasRercordCar(record, '新增违章')) {
          const param = {
            origin: 'short-order',
            carId: record.carId,
            orderId: record.id,
            orderNo: record.orderCode,
          }
          uni.navigateTo({ url: `/pages/asset/car-violation/components/add?${serializeUrlParams(param)}` })
        }
      },
    },
    {
      label: '新增维修',
      permission: 'svmsapp:order:short-order.repair',
      show: (record) => [200, 300, 1000].includes(record.orderStatus),
      method: (record) => {
        if (hasRercordCar(record, '新增维修')) {
          const param = {
            origin: 'short-order',
            carId: record.carId,
            orderId: record.id,
            orderNo: record.orderCode,
          }
          uni.navigateTo({ url: `/pages/asset/car-repair/form/index?${serializeUrlParams(param)}` })
        }
      },
    },
    {
      label: '押金退款',
      permission: 'svmsapp:order:short-order.depositrefuse',
      show: (record) => record.canBackDeposit,
      method: (record) => {
        uni.navigateTo({
          url: '/pages/order/short-order/detail/confirmExpenses?idList=' + JSON.stringify(record.depositFeeIdList) + '&pagefrom=orderList',
        })
      },
    },
    {
      label: '取消订单',
      permission: 'svmsapp:order:short-order.cancel',
      show: (record) => [10, 100].includes(record.orderStatus) && orderIsMaintenance(record),
      method: (record) => {
        uni.navigateTo({
          url:
            `/pages/order/short-order/detail/cancel-order?` +
            `id=${record.id}&startTime=${record.startTime}&endTime=${record.endTime}` +
            `&siteId=${record.siteId}&returnSiteId=${record.returnSiteId}` +
            `&sendServiceFlag=${record.sendServiceFlag}&returnServiceFlag=${record.returnServiceFlag}` +
            `&modelId=${record.carModelId}&type=4`,
        })
      },
    },
    {
      label: '订单改排',
      permission: 'svmsapp:order:short-order.replatooncar',
      show: (record) => [100].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
      method: (record) => {
        if (hasRercordCar(record, '改排')) {
          platoonCarFn(record)
        }
      },
    },
    {
      label: '添加报销单',
      permission: 'svmsapp:order:short-order.addreimbursement',
      show: (record) => record.reimbursementFlag === 1 && props.admin,
      method: (record) => {
        const orderParams = {
          refCostType: 2,
          businessType: 1,
          businessId: record.id,
          businessCode: record.orderCode,
          feeOrgId: record.siteId,
          feeOrgName: record.siteName,
          memberName: record.memberName, //承租人姓名
          memberPhone: record.memberPhone, //承租人电话
        }
        uni.navigateTo({
          url: `/pages/operate-cost/apply-form/index?orderParams=${JSON.stringify(orderParams)}`,
        })
      },
    },
    {
      label: '添加付款单',
      permission: 'svmsapp:order:short-order.addpayment',
      show: (record) => record.expenditureFlag === 1 && props.admin,
      method: (record) => {
        const orderParams = {
          refCostType: 2,
          businessType: 1,
          businessId: record.id,
          businessCode: record.orderCode,
          feeOrgId: record.siteId,
          feeOrgName: record.siteName,
          memberName: record.memberName, //承租人姓名
          memberPhone: record.memberPhone, //承租人电话
        }
        uni.navigateTo({
          url: `/pages/operate-cost/pay-form/index?orderParams=${JSON.stringify(orderParams)}`,
        })
      },
    },
    {
      label: '查看关联工单',
      permission: 'svmsapp:order:short-order.viewworkorder',
      show: (record) => record.workOrderList && record.workOrderList.length > 0,
      method: (record) => {
        uni.navigateTo({
          url: `/pages/order/components/workOrders`,
          success(res) {
            res.eventChannel.emit('acceptDataFromOpenedPage', {
              record,
            })
          },
        })
      },
    },
    {
      label: '修改车牌号',
      // v5.9.1.2 2024-08-23修改车牌号改为permission控制
      permission: 'svmsapp:order:short-order.editCarLicenseNo',
      show: (record) => (record.orderStatus == 100 && record.channelOrderMaintenance == 1) || [200, 300, 1000].includes(record.orderStatus),
      method: (record) => {
        editCarLicenseNo(record)
      },
    },
    {
      label: '合同记录',
      permission: 'svmsapp:order:short-order.contract',
      show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
      method: (record) => {
        uni.navigateTo({
          url: `/pages/order/short-order/detail/index?id=${record.id}&orderId=${record.id}&bizType=1&tab=contract`,
        })
      },
    },
    {
      label: '作废订单',
      permission: 'svmsapp:order:short-order.invalidorder',
      show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
      method: (record) => {
        invalidOrderFn(record)
      },
    },
    {
      label: '新增换车单',
      permission: 'svmsapp:order:short-order.addchangecarworkorder',
      show: (record) => record.isCarHouseKeepOpen === 1 && record.changeCarOrderFlag === 1 && record.orderStatus === 200,
      method: (record) => {
        uni.navigateTo({
          url: `/pages/work/workOrder/form/createChangeCarWorkOrder?refType=1&refId=${record.id}&refCode=${record.orderCode}&carId=${record.carId}&type=order`,
        })
      },
    },
    {
      label: '核实订单',
      permission: 'svmsapp:order:short-order.verifyOrder',
      show: (record) =>
        record.orderLabelList.includes('待审核') && userInfoStore.enterpriseDetail.config.orderLabelEnabledList?.includes(2),
      method: (record) => {
        uni.showModal({
          title: '确认核实订单?',
          cancelText: '取消',
          confirmText: '确认',
          success: (res) => {
            if (res.confirm) {
              verifyOrderApi({ id: record.id })
                .then(() => {
                  uni.showToast({
                    title: '核实成功',
                    icon: 'none',
                  })
                  emit('ok')
                })
                .catch((error) => {
                  uni.showToast({
                    title: error.message,
                    icon: 'none',
                  })
                })
            }
          },
        })
      },
    },
    {
      label: '订单好评',
      permission: 'svmsapp:order:short-order.comment',
      show: (record) => (record.orderStatus === 300 || record.orderStatus === 1000) && !record.orderLabelList?.includes('已好评'),
      method: (record) => {
        uni.showModal({
          title: '确认好评?',
          cancelText: '取消',
          confirmText: '确认',
          success: (res) => {
            if (res.confirm) {
              orderGoodEvaluate({ idList: [record.id], isCancel: 0 }).then(() => {
                uni.showToast({
                  title: '好评成功',
                })
                emit('ok')
              })
            }
          },
        })
      },
    },
    {
      label: '取消好评',
      permission: 'svmsapp:order:short-order.comment',
      show: (record) => (record.orderStatus === 300 || record.orderStatus === 1000) && record.orderLabelList?.includes('已好评'),
      method: (record) => {
        uni.showModal({
          title: '确认取消好评?',
          cancelText: '取消',
          confirmText: '确认',
          success: (res) => {
            if (res.confirm) {
              orderGoodEvaluate({ idList: [record.id], isCancel: 1 }).then(() => {
                uni.showToast({
                  title: '取消好评成功',
                })
                emit('ok')
              })
            }
          },
        })
      },
    },
    // 只有当长/短租订单关联了状态处于“未开始、待控车”的虚拟钥匙控车单时，才展示【发送控车钥匙短信】的按钮
    {
      label: '发送控车钥匙短信',
      permission: 'svmsapp:order:short-order.message',
      show: (record) => record.carControlOrderCount,
      method: (record) => {
        if (record.carControlOrderCount == 1) {
          uni.showModal({
            title: '确认发送控车钥匙短信吗？',
            cancelText: '取消',
            confirmText: '确认',
            success: (res) => {
              if (res.confirm) {
                // 发送类型   1：从短租发送   2：从长租发送   为空或其他值默认从虚拟控车单发送
                getCarControlSms({ id: record.carControlOrderId, type: 1 }).then((res) => {
                  uni.showToast({
                    title: res.result,
                    icon: 'none',
                  })
                  emit('ok')
                })
              }
            },
          })
        } else {
          uni.navigateTo({
            url: `/pages/order/short-order/message-modal?refCode=${record.orderCode || ''}&type=short`,
          })
        }
      },
    },

    // 当订单产生了关联控车单时，出现该按钮
    {
      label: '拦截虚拟车钥匙',
      permission: 'svmsapp:order:short-order.interceptRefControl',
      show: (record) => record.orderLabelList?.includes('虚拟车钥匙'),
      method: (record) => {
        uni.showModal({
          title: '确认拦截虚拟车钥匙?',
          cancelText: '取消',
          confirmText: '确认',
          success: (res) => {
            if (res.confirm) {
              getInterceptRefControl({ refType: 1, refId: record.id, refCode: record.orderCode }).then(() => {
                uni.showToast({
                  title: '拦截虚拟车钥匙成功',
                  icon: 'none',
                })
                emit('ok')
              })
            }
          },
        })
      },
    },
    {
      label: '重新下发车钥匙',
      permission: 'svmsapp:order:short-order.reCarKey',
      show: (record) => record.orderLabelList?.includes('虚拟车钥匙'),
      method: (record) => {
        uni.showModal({
          title: '确认重新下发车钥匙?',
          cancelText: '取消',
          confirmText: '确认',
          success: (res) => {
            if (res.confirm) {
              getReCarKey({ refType: 1, refId: record.id, refCode: record.orderCode }).then(() => {
                uni.showToast({
                  title: '重新下发车钥匙成功',
                  icon: 'none',
                })
                emit('ok')
              })
            }
          },
        })
      },
    },
    {
      label: '生成电子合同',
      permission: 'svmsapp:order:short-order.handContract',
      method: (record) => {
        handleGenerateContract(record)
      },
    },
    {
      label: '免押码',
      permission: 'svmsapp:order:short-order.freeDepositCode',
      show: (record) => record.freeDepositCodeShow == 1,
      method: (record) => {
        uni.navigateTo({
          url: `/pages/order/short-order/free-deposit-code?orderId=${record.id}`,
        })
      },
    },
  ])
</script>

<style lang="less" scoped>
  .order-btns-wrapper {
    padding: 0 24rpx;
    background-color: #fff;
    border-radius: 0 0 8rpx 8rpx;
  }
</style>
